package com.pxmeta.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.order.dto.OrderEvaluateDTO;
import com.pxmeta.order.entity.OrderEvaluate;
import com.pxmeta.order.entity.UserOrderRecord;
import com.pxmeta.order.mapper.OrderEvaluateMapper;
import com.pxmeta.order.mapper.UserOrderRecordMapper;
import com.pxmeta.order.service.IOrderEvaluateService;
import com.pxmeta.order.service.IUserOrderRecordService;
import com.pxmeta.order.vo.OrderDetailTagListVO;
import com.pxmeta.order.vo.OrderDetailVO;
import com.pxmeta.order.vo.OrderEvaluateVO;
import com.pxmeta.party.entity.SkillPrice;
import com.pxmeta.party.service.ISkillPriceService;
import com.pxmeta.skill.entity.UserSkill;
import com.pxmeta.skill.entity.enums.OrderStatusEnums;
import com.pxmeta.skill.entity.vo.OrderProgressVO;
import com.pxmeta.skill.service.IUserSkillService;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.UserTag;
import com.pxmeta.user.service.IUserService;
import com.pxmeta.user.service.IUserTagService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class OrderEvaluateServiceImpl extends ServiceImpl<OrderEvaluateMapper, OrderEvaluate> implements IOrderEvaluateService {

    private final IUserTagService tagService;


    /**
     * 获取订单评价
     * @param userId
     * @param orderId
     * @return
     */
    @Override
    public OrderEvaluateVO getEvaluate(Long userId, Long orderId) {
        OrderEvaluateVO vo = new OrderEvaluateVO();
        LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEvaluate::getOrderId, orderId)
                .eq(OrderEvaluate::getUserId, userId);

        OrderEvaluate evaluate = this.getOne(wrapper);

        if (null == evaluate){
            return null;
        }

        vo.setContent(evaluate.getContent());
        vo.setIsSatisfied(evaluate.getIsSatisfied());
        vo.setTime(evaluate.getCreateTime());
        String tagIds = evaluate.getTagIds();
        if (StringUtils.isNotBlank(tagIds)){
            List<String> tagIdList = Arrays.asList(tagIds.split(","));
            List<UserTag> tags = tagService.listByIds(tagIdList);
            List<String> tagNameList = tags.stream().map(UserTag::getName).collect(Collectors.toList());
            vo.setTags(tagNameList);
        }

        return vo;
    }

    @Override
    public Long getEvaluateCount(Long userId) {
        LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEvaluate::getTargetUserId, userId);
        return this.count(wrapper);
    }

    @Override
    public Double getSatisfiedRate(Long userId) {
        LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEvaluate::getTargetUserId, userId);
        List<OrderEvaluate> list = this.list(wrapper);

        int satisfiedCount = 0;
        for (OrderEvaluate orderEvaluate : list) {
            Boolean isSatisfied = orderEvaluate.getIsSatisfied();
            if (isSatisfied == null || isSatisfied){
                satisfiedCount++;
            }
        }
        if (list.size() == 0){
            return 100.0;
        }
        double rate = BigDecimal.valueOf((satisfiedCount / list.size())* 100L).setScale(1, RoundingMode.HALF_UP).doubleValue();
        return satisfiedCount == 0?100.0:rate;
    }

    @Override
    public List<OrderDetailTagListVO> getSkillDetailTags(Long userId, Integer skillId) {
        //获取所有评价
        LambdaQueryWrapper<OrderEvaluate> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(OrderEvaluate::getTargetUserId,userId)
                .eq(OrderEvaluate::getSkillId, skillId);
        List<OrderEvaluate> evaluates = this.list(wrapper);

        List<String> tagList = Lists.newLinkedList();
        //获取评价中所有标签
        evaluates.stream().map(OrderEvaluate::getTagIds).forEach(str->{
            if (StringUtils.isNotBlank(str)){
                tagList.addAll(Arrays.asList(str.split(",")));
            }
        });
        if (tagList.isEmpty()){
            return Lists.newArrayList();
        }

        List<UserTag> tags = tagService.listByIds(tagList);


        Map<String, Integer> map = new HashMap<>();

        // 计数，将List中的元素作为key，出现的次数作为value存储在Map中
        for (UserTag tag : tags) {
            map.put(tag.getName(), map.getOrDefault(tag.getName(), 0) + 1);
        }

        List<OrderDetailTagListVO> finalList = Lists.newLinkedList();
        // 输出重复数据以及它们的个数
        for (Map.Entry<String, Integer> entry : map.entrySet()) {
            String tag = entry.getKey();
            int count = entry.getValue();
            OrderDetailTagListVO vo = new OrderDetailTagListVO();
            vo.setTagName(tag);
            vo.setTagCount(count);
            finalList.add(vo);
        }

        return finalList;
    }
}
